#include "meegimsettings.h"

#include "MyXmppClient.h"

MeegIMSettings::MeegIMSettings(QObject *parent) : MySettings(parent)
{
    qmlObj = reinterpret_cast<QDeclarativeView*>(parent);

    jid_indx0 = "";
    pass_indx0 = "";
    dflt_indx0 = "";

    alm = new AccountsListModel( this );

    QDeclarativeEngine *engine = qmlObj->engine();
    engine->rootContext()->setContextProperty( "cppListOfAccounts", alm );
}

void MeegIMSettings::getDefaultAccount()
{
    QString passwd("");

    QStringList listAcc = getListAccounts();
    QStringList::const_iterator itr = listAcc.begin();
    while ( itr != listAcc.end() )
    {
        QString jid = *itr;
        itr++;

        passwd = getPasswd( jid );

        bool isDefault = isAccDefault( jid );
        if( isDefault ) {
            MyXmppClient::myPass = passwd;
            MyXmppClient::myJid = jid;
            return;
        }
    }
    return;
}


void MeegIMSettings::initListOfAccounts() //Q_INVOKABLE
{
    QStringList listAcc = getListAccounts();

    alm->removeRows( 0, alm->count() );

    QStringList::const_iterator itr = listAcc.begin();
    int i = 0;
    while ( itr != listAcc.end() )
    {
        QString jid = *itr;
        itr++;

        QString passwd = getPasswd( jid );
        QString icon = "qrc:/qml/images/accXMPP.png";

        bool isDefault = isAccDefault( jid );

        AccountsItemModel *aim = new AccountsItemModel( jid, passwd, icon, isDefault, this );
        alm->append(aim);

        if(i==0) {
            jid_indx0 = jid;
            pass_indx0 = passwd;
            dflt_indx0 = isDefault;
        }
        i++;
    }
}


void MeegIMSettings::setAccount( QString _jid, QString _pass, bool _isDflt ) //Q_INVOKABLE
{
    this->addAccount( _jid );
    this->setPasswd( _jid, _pass );
    this->setAccDefault( _jid, _isDflt );

    this->getDefaultAccount();
}


void MeegIMSettings::removeAccount( QString _jid ) //Q_INVOKABLE
{
    this->remAccount( _jid );
    this->remove( _jid );
}
